import React, { useState, useCallback, useRef, useEffect } from 'react';
import PropTypes from 'prop-types';
import api, { host } from 'api/config';
import { toast } from 'react-toastify';

import './style.scss';

const ImageUploadList = ({
    onFileChange,
    onDelete,
    initialImages = [],
    className = '',
    accept = 'image/*',
    disabled = false,
    text = '上传参考图',
    showDelete = true,
    maxCount = 3,
}) => {
    const [images, setImages] = useState(initialImages); // 图片预览 URL 数组
    const [files, setFiles] = useState([]); // 文件对象数组
    const inputRef = useRef(null);

    useEffect(() => {
        if (Array.isArray(initialImages)) {
            const validImages = initialImages.filter(
                (url) => typeof url === 'string' && url
            );
            setImages(validImages);
        }
    }, [initialImages]); // 当 initialImages 变化时更新状态

    const isValidFileName = (filename) => {
        // 检查是否包含非法字符
        const invalidChars = ['@', ' '];
        return !invalidChars.some((char) => filename.includes(char));
    };

    // 处理文件选择
    const handleFileChange = useCallback(
        (e) => {
            if (images.length >= maxCount) return;

            const selectedFile = e.target.files[0];
            if (selectedFile) {
                if (!isValidFileName(selectedFile.name)) {
                    toast.error(
                        '文件名包含非法字符 (@ 或空格)，请重新命名文件后再上传',
                        {
                            autoClose: 1000,
                            hideProgressBar: true,
                        }
                    );
                    // 不清空 input 值，让用户有机会重新选择文件
                    return;
                }
                processFile(selectedFile);
            }
        },
        [images, maxCount]
    );

    // 处理拖拽放下文件
    const handleDrop = useCallback(
        (e) => {
            e.preventDefault();
            if (images.length >= maxCount) return;

            const droppedFile = e.dataTransfer.files[0];
            if (droppedFile) {
                if (!isValidFileName(droppedFile.name)) {
                    toast.error(
                        '文件名包含非法字符 (@ 或空格)，请重新命名文件后再上传',
                        {
                            autoClose: 1000,
                            hideProgressBar: true,
                        }
                    );
                    return;
                }
                processFile(droppedFile);
            }
        },
        [images, maxCount]
    );

    const uploadToOSS = async (file) => {
        // 实现你的 OSS 上传逻辑

        const formData = new FormData();
        formData.append('file', file);

        for (let [key, value] of formData.entries()) {
            // console.log(key, value);
        }

        // const response = await fetch(`${host}/v1/tob/upload-image`, {
        //     method: 'POST',
        //     body: formData,
        // });
        const response = await api.post('/v1/tob/upload-image', formData, {
            headers: {
                'Content-Type': 'multipart/form-data',
            },
        });
        // console.log(response, 'result');
        const result = await response.data;

        // const result = await response.json();
        // 假设接口返回 { url: '图片链接' }
        return result.url;
    };

    // 统一处理文件
    const processFile = async (file) => {
        const url = await uploadToOSS(file);
        const newFiles = [...files, file];
        const newUrls = [...images, url];

        setFiles(newFiles);
        setImages(newUrls);

        onFileChange(newFiles, newUrls);
    };

    // 删除指定索引的图片
    const handleDelete = useCallback(
        (index, e) => {
            e.stopPropagation();

            const newImages = images.filter((_, i) => i !== index);
            const newFiles = files.filter((_, i) => i !== index);

            setImages(newImages);
            setFiles(newFiles);

            // 删除时也触发 onFileChange，传递当前剩余的 files 和 urls
            onFileChange(newFiles, newImages);

            if (onDelete) {
                onDelete(index);
            }

            // 安全地重置 input 值
            if (inputRef.current) {
                inputRef.current.value = '';
            }
        },
        [images, files, onFileChange, onDelete]
    );

    const handleDragOver = useCallback((e) => {
        e.preventDefault();
    }, []);

    // 动态计算 grid 列数
    const getGridColumns = () => {
        const count = images.length;
        if (count >= maxCount) return `repeat(${maxCount}, 1fr)`; // 当图片数量达到最大限制时，返回 maxCount 列
        if (count === 0) return '1fr';
        if (count === 1) return 'repeat(2, 1fr)';
        if (count === 2) return 'repeat(3, 1fr)';
        return `repeat(${count + 1}, 1fr)`; // 图片数量未达最大限制时，为上传按钮留一格
    };

    return (
        <div
            className={`file-upload-container-list ${className}`}
            onDrop={handleDrop}
            onDragOver={handleDragOver}
            style={{ gridTemplateColumns: getGridColumns() }}
        >
            {images.map((url, index) => (
                <div key={index} className="image-preview">
                    <img src={url} alt={`Preview ${index}`} />
                    {showDelete && (
                        <button
                            className="delete-button"
                            onClick={(e) => handleDelete(index, e)}
                            aria-label="删除图片"
                        >
                            <svg viewBox="0 0 24 24" width="16" height="16">
                                <path
                                    fill="currentColor"
                                    d="M19 6.41L17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"
                                />
                            </svg>
                        </button>
                    )}
                </div>
            ))}

            {/* 如果未达到最大上传数，则显示上传区域 */}
            {images.length < maxCount && (
                <div className="file-upload-text">
                    <input
                        type="file"
                        accept={accept}
                        onChange={handleFileChange}
                        className="file-input"
                        disabled={disabled}
                        ref={inputRef}
                    />
                    <img
                        src="https://img.alicdn.com/imgextra/i4/O1CN01uFSjFw28m9JwLypRT_!!6000000007974-55-tps-16-14.svg"
                        alt="上传图标"
                        style={{ marginBottom: '10px' }}
                    />
                    <p>{text}</p>
                </div>
            )}
        </div>
    );
};

ImageUploadList.propTypes = {
    onFileChange: PropTypes.func.isRequired,
    onDelete: PropTypes.func,
    className: PropTypes.string,
    accept: PropTypes.string,
    disabled: PropTypes.bool,
    text: PropTypes.string,
    showDelete: PropTypes.bool,
    maxCount: PropTypes.number,
};

export default ImageUploadList;
